<template>
    <div class="learn">
      <!--<CameraVideo/>-->
    <div>
    <div class="box1">
      <video
        id="videoCamera"
        class="canvas"
        :width="videoWidth"
        :height="videoHeight"
        autoPlay
      ></video>
      <canvas
        id="canvasCamera"
        class="canvas"
        :width="canvasWidth"
        :height="canvasHeight"
      ></canvas>
    </div>
  </div>
  <Warn v-if="showWarn" @close="showWarn=false" />
  <!--<CameraVideo/>-->
        <div class="main">
            <div class="main-left">
                <div class="left-back" @click="goBack">
                    <img src="../static/icons/back.png" />
                    后退
                </div>
                <div class="left-main">
                    <div class="left-title">
                        <img src="../static/icons/memory.png" />
                        学苑温习
                    </div>
                    <div class="left-counter">
                        <div class="left-number" style="color:#EACD76">{{wordLeft}}</div>
                        <span>待复习</span>
                        <img src="../static/icons/arrow.png" />
                        <div class="left-number" style="color:#80D1B9">{{wordReview}}</div>
                        <span>记忆模糊</span>
                        <img src="../static/icons/arrow.png" />
                        <div class="left-number" style="color:#23B26D">{{wordFinished}}</div>
                        <span>当前已记住</span>
                    </div>
                    <div class="left-rate"></div>
                </div>
            </div>
            <div class="learn-word">
                <div class="word-card" @click="cardClicked">
                    <div class="card-progress">
                        <div :style="'width:'+unitProgress+'%'" />
                    </div>
                    <div class="word-en"><div/><span>{{this.wordEn}}</span></div>
                    <div class="word-zh" :style="showZh?'':'opacity:0'">{{this.wordZh}}</div>
                </div>
                <div class="word-choice">
                    <template v-if="wordType==='learned'">
                        <div
                          class="button green"
                          @click="reviseCurrentWord(1)"
                          :style="showZh?'':'border:solid 2px #c0cace;color:#c0cace;'"
                        >
                            <div class="button-num"><span>1</span></div>
                            我记住啦
                        </div>
                        <div
                          class="button yellow"
                          @click="reviseCurrentWord(2)"
                          :style="showZh?'':'border:solid 2px #c0cace;color:#c0cace;'"
                        >
                            <div class="button-num"><span>2</span></div>
                            有点模糊
                        </div>
                        <div
                          class="button red"
                          @click="reviseCurrentWord(3)"
                          :style="showZh?'':'border:solid 2px #c0cace;color:#c0cace;'"
                        >
                            <div class="button-num"><span>3</span></div>
                            我不太会
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import cn from '@/api/cn'
import us from '@/api/us'
import Warn from '@/components/Warn'
import axios from 'axios'

export default {
  name: 'revise',
  components: {
    Warn
  },
  data () {
    return {
      // camera part
      showWarn: false,
    timer: 0,
    a: 0,
    os: false, //控制摄像头开关
    thisVideo: null,
    thisContext: null,
    thisCancas: null,
    imgSrc: "",
    videoWidth: 500,
    videoHeight: 400,
    canvasWidth:500,
    canvasHeight:400,
    // camera part
    userName:'',
      showZh: false,
      wordUnit: [],
      unitPointer: 0,
      wordLeft: 0,
      wordReview: 0,
      wordFinished: 0,
      wordTotalNum: 0,
      wordList: '',
      wordType: '',
      wordEn: '',
      wordZh: 'hh'
    }
  },
  created () {
    console.log('Cn.vue打开摄像头')
    this.openCamera();
    this.setUserName() // 设置当前用户名
    console.log('设置当前用户名')
  },
  mounted () {
    this.global.sendcamera = setInterval(this.ongoing, 3000);
    this.global.sendfocus = setInterval(this.sendFocus, 10000);
    console.log('开始复习')
    setTimeout(() => {
      this.getNextUnit()
      this.setStatusNums()
      cn.reportUserLearned().then(res => console.log(res)) // beta版测试用
    }, 200)
    document.onkeydown = (event) => {
      switch (event.keyCode) {
        case 32: // space
          this.cardClicked()
          break
        case 49: // num 1
          this.reviseCurrentWord(1)
          break
        case 50: // num 2
          this.reviseCurrentWord(2)
          break
        case 51: // num 3
          this.reviseCurrentWord(3)
          break
      }
    }
  },
  computed: {
    // progress () { // 这种算法得到的进度不太准
    //   return (100 * (this.wordReview * 0.3 + this.wordFinished) / this.wordTotalNum).toFixed(2)
    // },
    unitProgress () {
      return 100 * ((this.unitPointer / this.wordUnit.length) || 0)
    }
  },
  beforeDestroy(){
    console.log('离开页面Cn')
    this.stopCamera();
  },
  methods: {
    // camera part
  ongoing(){
    if(this.global.camerafeedback === 1){
      console.log('摄像头ongoing')
      this.global.camerafeedback = 0
      this.photographBtn();
      this.submitBtn();
    }
    },
    submitBtn() {
      // console.log('Into submitBtn');
      var dataToSend = {
          'imgData': this.imgSrc
      };
      var url = this.global.cameraip
      this.$http.post(url +'/api/img', dataToSend).then(res => {
          var focus = JSON.parse(JSON.stringify(res.data))
          console.log('Cnfocus'+(focus.focus));
          this.global.camerafeedback = 1
          if (focus.focus===1) {
            this.global.unfocus += 1
          }else{
            this.global.focus += 1
          }
      });
    },
    openCamera() {
      // console.log('Into openCamera')
      this.$nextTick(() => {
        const _this = this;
        this.os = false;
        this.thisCancas = document.getElementById("canvasCamera");
        this.thisContext = this.thisCancas.getContext("2d");
        this.thisVideo = document.getElementById("videoCamera");
        if (navigator.mediaDevices === undefined) {
          navigator.mediaDevices = {};
        }
        if (navigator.mediaDevices.getUserMedia === undefined) {
          navigator.mediaDevices.getUserMedia = function (constraints) {
            let getUserMedia =
              navigator.webkitGetUserMedia ||
              navigator.mozGetUserMedia ||
              navigator.getUserMedia;
            if (!getUserMedia) {
              return Promise.reject(
                new Error("getUserMedia is not implemented in this browser")
              );
            }
            return new Promise(function (resolve, reject) {
              getUserMedia.call(navigator, constraints, resolve, reject);
            });
          };
        }
        const constraints = {
          audio: false,
          video: {
            width: _this.videoWidth,
            height: _this.videoHeight,
            transform: "scaleX(-1)",
          },
        };
        // console.log('aboutTo navigator.mediaDevices')
        navigator.mediaDevices.getUserMedia(constraints)
          .then(function (stream) {
            if ("srcObject" in _this.thisVideo) {
              // console.log('in _this.thisVideo')
              _this.thisVideo.srcObject = stream;
            } else {
              _this.thisVideo.src = window.URL.createObjectURL(stream);
            }
            _this.thisVideo.onloadedmetadata = function () {
              _this.thisVideo.play();
            };
          })
          .catch((err) => {
            console.log(err);
            this.$message({
              message: "没有开启摄像头权限或浏览器版本不兼容",
              type: "warning",
            });
          });
      });
    },
    photographBtn() {
      // 点击，canvas画图
      this.thisContext.drawImage(
        this.thisVideo,
        0,
        0,
        this.videoWidth,
        this.videoHeight
      );
      // 获取图片base64链接 >>> 这里是base64格式的图片
      this.imgSrc = this.thisCancas.toDataURL("image/png");
    },
    //清空画布
    clearCanvas(id) {
      let c = document.getElementById(id);
      let cxt = c.getContext("2d");
      cxt.clearRect(0, 0, c.width, c.height);
    },
    //重置画布
    resetBtn() {
      this.imgSrc = "";
      this.clearCanvas("canvasCamera");
    },
    //关闭摄像头
    stopCamera() {
      if (this.thisVideo && this.thisVideo !== null) {
        this.thisVideo.srcObject.getTracks()[0].stop();
        this.os = true; //切换成打开摄像头
      }
    },
    downloadFile(fileName, content) {
        let aLink = document.createElement('a');
        let blob = this.base64ToBlob(content); //new Blob([content]);
        aLink.download = fileName;
        aLink.href = URL.createObjectURL(blob);
        aLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));//兼容火狐
    }, 
    base64ToBlob(code) {
        let contentType = code.split(':')[1];
        let raw = window.atob(code);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for (let i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], { type: contentType });
    },
    downloadpic(){
      this.downloadFile("/hi.png",this.imgSrc)
    },
    sendFocus () {
    console.log('sendFocus')
    var http = axios.create({
            baseURL: "^/api", 
            timeout: 30000,
            headers: {"Content-Type": "application/json"}  
        });
        let url = "/api/focus"; 
        var ip = this.global.ip
        http.post(ip + url, {
            userName: this.userName,
            notplay: this.global.focus,            
            play: this.global.unfocus
        })
        .then(response => {  
            console.log('focus: ' + this.global.focus)
            console.log('unfocus: ' + this.global.unfocus)
            if(this.global.focus < this.global.unfocus){
              this.showWarn = true
            }
            this.global.focus = 1
            this.global.unfocus = 0
            // console.log(response.data);
        })
        .catch(error => {
            this.global.focus = 1
            this.global.unfocus = 0
            console.log('Error:', error);
            if (error.response) {
            console.log('Response data:', error.response.data);}
        });
  },
  // camera part
    getNextWord () {
      if (this.wordUnit.length && this.unitPointer < this.wordUnit.length) {
        const word = this.wordUnit[this.unitPointer]
        // console.log('this.getNextWord')
        // console.log(word)
        this.showZh = false
        this.wordType = word.type
        this.wordEn = word.wordEn
        this.wordZh = word.wordZh
        this.unitPointer += 1
        this.setStatusNums() // 每次切换下一个词都调用这个比较费资源，临时解决方案
      } else if (this.wordUnit.length) {
        this.getNextUnit()
      } else {
        this.showZh = false
        this.wordType = ''
        this.wordEn = '没有更多单词需要复习啦'
        this.wordZh = ''
        this.unitPointer = 0
        this.setStatusNums()
      }
      // us.getLearned().then(learned => console.log(this.wordEn, learned[this.wordEn])) // beta版测试用
    },
    getNextUnit () {
      cn.getNextUnitFromLearned().then((unit) => {
        this.unitPointer = 0
        this.wordUnit = unit
        // console.log('unit')
        // console.log(unit)
        this.getNextWord()
      }).catch(err => console.log(err))
    },
    reviseCurrentWord (knowType) {
      if (!this.showZh) return
      if (this.wordType !== 'learned') return
      cn.reviseWordFromLearned(this.wordEn, knowType, 'revise').then(() => {
        this.getNextWord()
      }).catch(err => console.log(err))
    },
    setStatusNums () { // 时间复杂度比较高，以后得改
      us.getLearned().then((learn) => {
        var learned = JSON.parse(JSON.stringify(learn.data))
        let wordLeft = 0
        let wordReview = 0
        let wordFinished = 0
        for (let key in learned) {
          let { period, updatedAt } = learned[key] || {}
          if (!period || !updatedAt || period > 9) continue
          // period大于9被认为是已经完全记住，不需要再复习
          if (period === 1) wordLeft += 1
          else if (period === 2) wordReview += 1
          else if (period > 2) {
            const timeDiff = Date.now() - updatedAt
            if (timeDiff > cn.getPeriodTime(period)) wordLeft += 1
            else wordFinished += 1
          }
        }
        this.wordLeft = wordLeft
        this.wordReview = wordReview
        this.wordFinished = wordFinished
      }).catch(err => console.log(err))
    },
    cardClicked () {
      this.showZh = !this.showZh
      console.log('en')
      console.log(this.wordEn)
      console.log('zh')
      console.log(this.wordZh)
    },
    goBack () {
    clearInterval(this.global.sendfocus);
    clearInterval(this.global.sendcamera);
    this.stopCamera()
    this.global.sendfocus = 0
    this.global.sendcamera = 0
    this.$router.go(-1)
    },
    setUserName(){
    cn.getUserName().then((res) => {
      this.userName = res
    }).catch(err => console.log(err))
  }
  }
}
</script>

<style scoped>
/* camera part */
#canvasCamera{
  margin-left: 20px;
}
.box1{
  background:rgba(249,93,62,0.1)
}
.canvas {
  display: none;/* xujiawei是大神*/
}
/* camera part */
.learn {
  width: 100vw;
  height: 100vh;
  background: #F0F0F0;
}

.main {
  height: 100%;
  max-width: 1300px;
  margin: 0 auto;
  position: relative;
}

.main-left {
  width: 220px;
  background: #FFFFFF;
  position: absolute;
  left: 0;
  top: 80px;
  bottom: 0;
  box-shadow: 4px 0 18px 0 rgba(0,0,0,.28);
}

.left-back {
  width: 100%;
  height: 55px;
  padding: 0 20px;
  box-sizing: border-box;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  font-size: 14px;
  letter-spacing: 1.5px;
  color: #455358;
  font-weight: 600;
  cursor: pointer;
}

.left-back img {
  width: 16px;
  height: 16px;
  margin-right: 7px;
  margin-top: 2px;
}

.left-main {
  width: 100%;
  padding-top: 30px;
  display: flex;
  flex-direction: column;
}

.left-title {
  display: flex;
  height: 50px;
  align-items: center;
  font-size: 14px;
  letter-spacing: 1.5px;
  font-weight: 600;
  color: #455358;
  padding: 0 20px;
  box-sizing: border-box;
}

.left-title img {
  width: 28px;
  height: 28px;
  margin-right: 4px;
}

.left-counter {
  width: 100%;
  height: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  margin-top: 50px;
}

.left-number {
  color: #455358;
  font-weight: 700;
  font-size: 20px;
}

.left-counter span {
  color: #455358;
  font-size: 12px;
  font-weight: 600;
}

.left-counter img {
  width: 28px;
  height: 28px;
}

.left-rate {
  position: absolute;
  bottom: 0;
  height: 80px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #455358;
  font-size: 20px;
  font-weight: bolder;
}

.learn-word {
  position: absolute;
  left: 220px;
  right: 0;
  top: 80px;
  bottom: 0;
  padding: 30px;
  box-sizing: border-box;
}

.word-card {
  width: 100%;
  height: 75%;
  background: #FFFFFF;
  position: relative;
  cursor: pointer;
}

.card-progress {
  position: absolute;
  top: 0;
  width: 100%;
  height: 5px;
  background: rgb(128, 209, 185);
}

.card-progress div {
  height: 100%;
  background: #40BC96;
  transition: all 0.2s;
}

.word-en,
.word-zh {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  left: 0;
  color: #455358;
}

.word-zh {
  height: calc(64% - 100px);
  margin: 50px 0;
  font-size: 23px;
  line-height: 30px;
  padding: 0 18%;
  overflow-x: hidden;
  overflow-y: auto;
  box-sizing: border-box;
  font-family: "Microsoft YaHei" !important;
  text-align: left;
  align-items: center;
  justify-content: flex-start;
  white-space: pre-line;
}

.word-en {
  font-size: 26px;
  height: 36%;
  font-family: TimesNewRoman !important;
}

.word-en div {
  width: 100%;
  height: 80%;
}

.word-en span {
  width: 100%;
  text-align: center;
  flex-shrink: 0;
}

.word-choice {
  width: 100%;
  height: 72px;
  margin-top: 40px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-left: 5px;
  box-sizing: border-box;
}

.button {
  width: 30%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 19px;
  font-weight: 700;
  letter-spacing: 1px;
  cursor: pointer;
  position: relative;
  transition: all 0.4s ease;
}

.new {
  width: 100%;
  border: solid 2px #3CCFCF;
  color: #455358;
}

.green {
  border: solid 2px #90c0ac;
  color: #90c0ac;
}

.yellow {
  border: solid 2px #e0a143;
  color: #e0a143;
}

.red {
  border: solid 2px #cd6c48;
  color: #cd6c48;
}

.button-num {
  width: 20px;
  height: 20px;
  position: absolute;
  left: -10px;
  top: -4px;
  background: #F0F0F0;
  padding: 3px 2px;
}

.button-num span {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 2px solid #c0cace;
  box-sizing: border-box;
  color: #c0cace;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 700;
}
</style>
